<template>
    <el-dialog
        class="ba-operate-dialog"
        :close-on-click-modal="false"
        :model-value="baTable.form.operate == 'feeitem'"
        @close="onClosed();baTable.toggleForm"
        @open="onOpen"
        v-loading="loading"
        width="70%"
    >
        <template #header>
            <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">
                预算设置 - {{ baTable.form.items!.title }}
            </div>
        </template>
        <div class="container">
            <div class="warp-item">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <div class="title">费用项</div>
                        <div class="tree-warp">
                            <el-scrollbar>
                                <el-tree ref="treeRef" :data="feeitemLists" node-key="id" :show-checkbox="true" :props="{label:'title'}" @check="handleNodeClick" />
                            </el-scrollbar>
                        </div>
                    </el-col>
                    <el-col :span="18">
                        <div class="title">预算</div>
                        <div class="table-warp">
                            <el-tabs v-model="tabModel" @tab-click="tabsClick">
                                <el-tab-pane :label="item.title" :name="`table${item.id}`" :key="index" v-for="(item, index) in tableData">
                                    <el-table
                                        :data="item.children"
                                        style="width: 100%"
                                        :height="tableHeight"
                                        :default-sort="{ prop: 'feeitem_id', order: 'ascending' }"
                                        @cell-click="onCellClick" :ref="(el) => setTableRef(el, item)">
                                        <el-table-column prop="title" width="180" label="费用项" >
                                            <template #default="{ row, column }">
                                                <template v-if="row.id > 100000">
                                                    <el-input type="text" size="small" ref="inputRef" @blur="inputBlur" @input="inputInput" id="table-input" v-model="row[column.property]" v-if="tableEditKey == `${row.pid}-${row.id}-${column.property}`"></el-input>
                                                    <template v-else>
                                                        <div class="table-input-item">
                                                            <el-text>{{row[column.property]}}</el-text>
                                                            <!-- <Icon name="fa fa-edit" size="14" color="#ccc"/> -->
                                                        </div>
                                                    </template>
                                                </template>
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="unit" label="UNIT" width="100" >
                                            <template #default="{ row, column }">
                                                <el-input type="number" step="0.01" size="small" ref="inputRef" @blur="inputBlur" @input="inputInput" id="table-input" v-model.number="row[column.property]" v-if="tableEditKey == `${row.pid}-${row.id}-${column.property}`"></el-input>
                                                <template v-else>
                                                    <div class="table-input-item">
                                                        <el-text>{{row[column.property]}}</el-text>
                                                        <!-- <Icon name="fa fa-edit" size="14" color="#ccc"/> -->
                                                    </div>
                                                </template>
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="qty" label="QTY" width="100" >
                                            <template #default="{ row, column }">
                                                <el-input type="number" step="0.01" size="small" ref="inputRef" @blur="inputBlur" @input="inputInput" id="table-input" v-model.number="row[column.property]" v-if="tableEditKey == `${row.pid}-${row.id}-${column.property}`"></el-input>
                                                <template v-else>
                                                    <div class="table-input-item">
                                                        <el-text>{{row[column.property]}}</el-text>
                                                        <!-- <Icon name="fa fa-edit" size="14" color="#ccc"/> -->
                                                    </div>
                                                </template>
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="trems" label="TREMS" width="100" >
                                            <template #default="{ row, column }">
                                                <!-- <el-input type="number" step="0.01" size="small" ref="inputRef" @blur="inputBlur" @input="inputInput" id="table-input" v-model.number="row[column.property]" v-if="tableEditKey == `${row.pid}-${row.id}-${column.property}`"></el-input> -->
                                                <el-autocomplete v-model="row[column.property]" size="small" @blur="inputBlur" :fetch-suggestions="tremsQuerySearch" clearable id="table-input" v-if="tableEditKey == `${row.pid}-${row.id}-${column.property}`"/>
                                                <template v-else>
                                                    <div class="table-input-item">
                                                        <el-text>{{row[column.property]}}</el-text>
                                                        <!-- <Icon name="fa fa-edit" size="14" color="#ccc"/> -->
                                                    </div>
                                                </template>
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="rate" label="RATE" width="100" >
                                            <template #default="{ row, column }">
                                                <el-input type="number" step="0.01" size="small" ref="inputRef" @blur="inputBlur" @input="inputInput" id="table-input" v-model.number="row[column.property]" v-if="tableEditKey == `${row.pid}-${row.id}-${column.property}`"></el-input>
                                                <template v-else>
                                                    <div class="table-input-item">
                                                        <el-text>{{row[column.property]}}</el-text>
                                                        <!-- <Icon name="fa fa-edit" size="14" color="#ccc"/> -->
                                                    </div>
                                                </template>
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="budget" label="预算" width="100" >
                                            <template #default="{ row }">
                                                {{row.budget}}
                                                <!-- <el-input type="number" step="0.01" size="small" ref="inputRef" @blur="inputBlur" @input="inputInput" id="table-input" v-model.number="row.budget" v-if="tableEditKey == `${row.pid}-${row.id}-budget`"></el-input>
                                                <el-text v-else>{{row.budget}}</el-text> -->
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="calculate" label="核算" width="100" />
                                        <el-table-column fixed="right" label="操作" width="120">
                                            <template #default="scope">
                                                <el-popover :visible="popVisible == `popVisible${scope.row.id}`" placement="top" :width="160">
                                                    <div style="padding:10px 0">确认删除?</div>
                                                    <div style="text-align: right; margin: 0">
                                                        <el-button size="small" @click="popVisible = ''">取消</el-button>
                                                        <el-button size="small" type="primary" @click.prevent="popVisible = '';deleteRow(scope.row.pid, scope.row.id, scope.$index)">确认</el-button>
                                                    </div>
                                                    <template #reference>
                                                        <el-button link type="primary" size="small" @click="popVisible = `popVisible${scope.row.id}`">删除</el-button>
                                                    </template>
                                                </el-popover>
                                            </template>
                                        </el-table-column>
                                    </el-table>
                                    <div class="add-item">
                                        <table>
                                            <tr>
                                                <td colspan="5" width="580">
                                                    <el-button class="add-btn" :icon="Plus" @click="addFeeItem">添加备用栏费用项</el-button>
                                                </td>
                                                <td width="100" style="padding: 0 12px;">{{ item.budget}}</td>
                                                <td width="100" style="padding: 0 12px;">{{ item.calculate}}</td>
                                            </tr>
                                        </table>
                                    </div>
                                </el-tab-pane>
                            </el-tabs>
                        </div>
                    </el-col>
                </el-row>
            </div>
        </div>
        <template #footer>
            <div :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'">
                <el-row>
                    <el-col :span="6">
                        <el-button v-blur @click="projectSelPop = true" type="warning">
                            复制项目预算
                        </el-button>
                    </el-col>
                    <el-col :span="18">
                        <el-button @click="onClosed">{{ t('Cancel') }}</el-button>
                        <el-button v-blur :loading="baTable.form.submitLoading" @click="submit()" type="primary">
                            保存
                        </el-button>
                        <el-button v-blur :loading="baTable.form.submitLoading" @click="submitAndProcess()" type="success">
                            保存并提交审批
                        </el-button>
                    </el-col>
                </el-row>
            </div>
        </template>

        <el-dialog v-model="projectSelPop" title="选择要复制的项目" width="500">
            <div class="container" style="padding-top:20px">
                <el-form>
                    <el-form-item label="项目">
                        <el-select v-model="copayProjectId" placeholder="请选择要复制的项目" size="large" style="width: 240px" >
                            <el-option v-for="item in projectLists" :key="item.id" :label="item.title" :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label=" ">
                        <el-button v-blur @click="copyHand()" type="primary">
                            确定
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-dialog>
    </el-dialog>
</template>

<script setup lang="ts">
interface Tree {
    title: string
    children?: Tree[]
}

interface tableData {
    id: number
    title: string
    pid: number
    unit: number
    qty: number
    trems: string
    rate: number
    budget: number
    calculate: number
    children?: tableData[]
}

interface nodes {
    id: number
    pid: number
    title: string
    remark: string
    $treeNodeId: number
}

import type { FormInstance, FormItemRule, TabsPaneContext, TreeNode  } from 'element-plus'
import { ElMessage, ElLoading  } from 'element-plus'
import { inject, reactive, ref, onMounted, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
import { useConfig } from '/@/stores/config'
import type baTableClass from '/@/utils/baTable'
import { getFeeitemList, updateProjectFeeitem, getProjectFeeitem, projectToAudit } from '/@/api/backend/index'
import { Plus } from '@element-plus/icons-vue'
import { randomNum } from '/@/utils/random'
import { getProjects } from '/@/api/backend'

const config = useConfig()
const formRef = ref<FormInstance>()
const treeRef = ref()
const baTable = inject('baTable') as baTableClass
const tableHeight = ref()
const { t } = useI18n()
const inputRef = ref()
let tableRefs = {}
let feeitemListsAll: tableData[] = []
const projectSelPop = ref(false)
const projectLists = ref([])
const copayProjectId = ref()
const loading = ref(false)
let LoadinServ = null

onMounted(() => {
    tableHeight.value = window.innerHeight * 0.6 - 187;
    getFeeitemList().then(res => {
        const tempDatas: any[] = []
        res.data.list.forEach((item: any) => {
            tempDatas.push({
                id: item.id,
                title: item.title,
                pid: item.pid,
                disabled: false,
                children: []
            })
            const index = tempDatas.length - 1
            item.children?.forEach((ele: any) => {
                tempDatas[index]['children'].push({
                    id: ele.id,
                    title: ele.title,
                    pid: ele.pid,
                    disabled: false,
                })
            })
            feeitemListsAll.push(item)
            feeitemListsAll = [...feeitemListsAll, ...item['children']]
        })
        tabModel.value = `table${feeitemListsAll[0]['id']}`
        feeitemLists = tempDatas
    })

    getProjects().then((res: any) => {
        projectLists.value = res.data.list
    })
})

let feeitemLists: nodes[] = []
let tableData: any = ref([])
let tableTotal: any = ref([])
let tabModel = ref('')
let tableEditKey = ref('')
let lastCheckNodeKeys: any = {}
let inputValue = ''
let popVisible = ref('')
let tabsIndex = 0
const onOpen = () => {
    toGetProjectFees(baTable.form.items!.id)
}
const showLoading = () => {
    LoadinServ = ElLoading.service({
        target: '.container',
        lock: false
    })
}
const toGetProjectFees = (project_id: number) => {
    showLoading()
    getProjectFeeitem({project_id: project_id}).then((res: any) => {
        const { list } = res.data
        list.forEach((item: any) => {
            let ele = {
                id: item.feeitem_id,
                title: item.feeitem_name,
                pTitle: item.feeitem_pname,
                pid: item.feeitem_pid,
                unit: item.unit,
                qty: item.qty,
                trems: item.trems,
                rate: item.rate,
                budget: item.budget,
                calculate: item.calculate,
            }
            setTableDataItem(ele)
            treeRef.value.setChecked(ele.id, true)
        })
        tableData.value.sort((a: any, b: any) => {
            return b.id - a.id
        })
        tabModel.value = `table${tableData.value[0]['id']}`
        LoadinServ.close()
    })
}
const handleNodeClick = (row: nodes) => {
    tabModel.value = `table${row.pid == 0 ? row.id : row.pid}`
    let nodes: nodes[] = treeRef.value.getCheckedNodes(true)
    for(let key in lastCheckNodeKeys){
        if(nodes.findIndex(p => p.id == Number(key)) == -1){
            const pIndex = tableData.value.findIndex((p: any) => p.id == lastCheckNodeKeys[key])
            tabsIndex = pIndex
            const cIndex = tableData.value[pIndex]['children']?.findIndex((p: any) => p.id == Number(key))
            tableData.value[pIndex]['children']?.splice(cIndex, 1)
        }
    }
    nodes.forEach((ele) => {
        lastCheckNodeKeys[String(ele.id)] = ele.pid;
        setTableDataItem(ele)
    })
    tableData.value.sort((a: any, b: any) => {
        return b.id - a.id
    })
}

const setTableDataItem = (ele: any) => {
    const pIndex = tableData.value.findIndex((p: any) => p.id == ele.pid)
    const budget = ele.budget ? Number(ele.budget) : 0
    const calculate = ele.calculate ? Number(ele.calculate) : 0

    if(pIndex == -1){
        let pTitle = ele.pTitle ? ele.pTitle : feeitemListsAll.find((p: any) => p.id == ele.pid)['title']
        tableData.value.push({
            id: ele.pid,
            title: pTitle,
            pid: 0,
            budget: budget,
            calculate: calculate,
            children: [
                {
                    id: ele.id,
                    title: ele.title,
                    pid: ele.pid,
                    unit: ele.unit ? ele.unit : 0,
                    qty: ele.qty ? ele.qty : 0,
                    trems: ele.trems ? ele.trems : '',
                    rate: ele.rate ? ele.rate : 0,
                    budget: budget,
                    calculate: calculate,
                }
            ]
        })
    } else {
        const cIndex = tableData.value[pIndex]['children']?.findIndex((p: any) => p.id == ele.id)
        if(cIndex == -1){
            tableData.value[pIndex]['budget'] += Number(budget)
            tableData.value[pIndex]['calculate'] += Number(calculate)
            tableData.value[pIndex]['children']?.push({
                id: ele.id,
                title: ele.title,
                pid: ele.pid,
                unit: ele.unit ? ele.unit : 0,
                qty: ele.qty ? ele.qty : 0,
                trems: ele.trems ? ele.trems : '',
                rate: ele.rate ? ele.rate : 0,
                budget: budget,
                calculate: calculate,
            })
            tableData.value[pIndex]['children'].sort((a:any, b:any) => {
                if(a.id > 10000){
                    return a.id - b.id
                } else {
                    return b.id - a.id
                }
            })
        }
    }
}

const deleteRow = (pid: number, id: number, index: number) => {
    const pIndex = tableData.value.findIndex((p: any) => p.id == pid)
    tableData.value[pIndex]['children'].splice(index, 1)
    treeRef.value.setChecked(id, false)
}

const onCellClick = (row: any, column: any, cell: any, event: any) => {
    tableEditKey.value = `${row.pid}-${row.id}-${column.property}`
    inputValue = row[column.property]
    nextTick(() => {
        document.getElementById('table-input')?.focus()
    })
}

const inputBlur = (event: FocusEvent) => {
    tableEditKey.value = ``
}

const inputInput = (value: string | number) => {
    let val = value
    const keys = tableEditKey.value.split('-')
    const property = keys[2]
    if(property != 'title') {
        val = Math.max(Number(Number(value).toFixed(2)), 0)
    }
    const pIndex = tableData.value.findIndex((p: any) => p.id == keys[0])
    const cIndex = tableData.value[pIndex]['children'].findIndex((p: any) => p.id == keys[1])
    tableData.value[pIndex]['children'][cIndex][property] = val
    let { unit, qty, rate } = tableData.value[pIndex]['children'][cIndex]
    // rate = parseFloat(rate).toFixed(2)
    // tableData.value[pIndex]['children'][cIndex]['rate'] = rate
    tableData.value[pIndex]['children'][cIndex]['budget'] = Number((unit * qty * Number(rate)).toFixed(2))
    let total_budget = 0
    tableData.value[pIndex]['children'].forEach((item: any) => {
        total_budget += Number(item.budget)
    })
    tableData.value[pIndex].budget = total_budget
}

const submit = (hasProcess: boolean = false) => {
    const datas: any[] = [];
    tableData.value.forEach((item: tableData) => {
        item.children?.forEach((ele: tableData) => {
            const pFeeitem = feeitemListsAll.find((p: any) => p.id == ele.pid)
            datas.push({
                project_id: baTable.form.items!.id,
                feeitem_id: ele.id,
                feeitem_name: ele.title,
                feeitem_pid: ele.pid,
                feeitem_pname: pFeeitem?.title,
                unit: ele.unit ? ele.unit : 0,
                qty: ele.qty ? ele.qty : 0,
                trems: ele.trems ? ele.trems : '',
                rate: ele.rate ? ele.rate : 0,
                budget: ele.budget,
                calculate: ele.calculate,
            })
        })
    })
    baTable.form.submitLoading = true
    updateProjectFeeitem({project_id: baTable.form.items!.id, lists: datas}).then((res: any) => {
        if(hasProcess) {
            projectToAudit({project_id: baTable.form.items!.id}).then((res: any) => {
                ElMessage({
                    message: '保存成功',
                    type: 'success',
                })
                setTimeout(() => {
                    baTable.toggleForm()
                }, 1000)
            })
        } else {
            ElMessage({
                message: '保存成功',
                type: 'success',
            })
            setTimeout(() => {
                baTable.toggleForm()
            }, 1000)
        }
    })
}

const submitAndProcess = () => {
    submit(true)
}

const tremsQuerySearch = (queryString: string, cb: any) => {
    cb([{value: 'day'}, {value: 'case'}, {value: 'per'}])
}

const tabsClick = (pane: TabsPaneContext) => {
    tabsIndex = Number(pane.index)
}

const setTableRef = (el: any, row) => {
    if (el) {
        const key = `table${row.id}`
        tableRefs[key] = el
    }
};

const addFeeItem = () => {
    tableData.value[tabsIndex]['children']?.push({
        id: randomNum(10000000,99999999),
        title: '备用栏',
        pid: tableData.value[tabsIndex].id,
        unit: 0,
        qty: 0,
        trems: '',
        rate: 0,
        budget: 0,
        calculate: 0,
    })
    nextTick(() => {
        let scrollTop = (tableData.value[tabsIndex]['children'].length + 1) * 42
        tableRefs[tabModel.value].setScrollTop(scrollTop)
    })
}

const onClosed = () => {
    baTable.toggleForm()
    tableData.value = []
    baTable.form.submitLoading = false
    Object.values(lastCheckNodeKeys).forEach((id: any) => {
        treeRef.value.setChecked(id, false)
    })
}

const copyHand = () => {
    tableData.value = []
    loading.value = true
    toGetProjectFees(Number(copayProjectId.value))
    projectSelPop.value = false
}
</script>

<style scoped lang="scss">
    .ba-operate-dialog .el-dialog__body { padding-bottom: 0; }
    .tree-warp { border-right: 1px solid #ddd; height: calc(60vh - 87px);}
    .table-warp { }
    .title { font-size: 14px; font-weight: bold; padding: 8px 0; }

    .table-input-item { display: flex;
    justify-content: space-between;
    align-items: center;
    border: 1px dashed #eee;
    padding-left: 5px;
    height: 25px;}
    .add-item { padding-top: 5px; display: flex; }
    .add-item .add-btn { flex: 1; border: 1px dashed #eee; }
</style>
